package api

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"schedulingsystem/backend/models"
)

// ShiftHandler 处理班次相关的API请求
type ShiftHandler struct {
	DB *gorm.DB
}

// NewShiftHandler 创建一个新的班次处理器
func NewShiftHandler(db *gorm.DB) *ShiftHandler {
	return &ShiftHandler{DB: db}
}

// GetShifts 获取所有班次
func (h *ShiftHandler) GetShifts(c *gin.Context) {
	var shifts []models.Shift
	result := h.DB.Find(&shifts)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取班次列表失败"})
		return
	}

	c.JSON(http.StatusOK, shifts)
}

// GetShift 获取单个班次
func (h *ShiftHandler) GetShift(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的班次ID"})
		return
	}

	var shift models.Shift
	result := h.DB.First(&shift, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "班次不存在"})
		return
	}

	c.JSON(http.StatusOK, shift)
}

// CreateShift 创建新班次
func (h *ShiftHandler) CreateShift(c *gin.Context) {
	var shift models.Shift
	if err := c.ShouldBindJSON(&shift); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的班次数据"})
		return
	}

	// 确保时间格式正确
	if shift.StartTime.IsZero() || shift.EndTime.IsZero() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "开始时间和结束时间不能为空"})
		return
	}

	// 如果不是全天班次，确保结束时间晚于开始时间
	if !shift.IsFullDay {
		// 提取时间部分进行比较
		startHour, startMin, _ := shift.StartTime.Clock()
		endHour, endMin, _ := shift.EndTime.Clock()

		if endHour < startHour || (endHour == startHour && endMin <= startMin) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "下班时间必须晚于上班时间"})
			return
		}
	}

	result := h.DB.Create(&shift)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建班次失败"})
		return
	}

	c.JSON(http.StatusCreated, shift)
}

// UpdateShift 更新班次信息
func (h *ShiftHandler) UpdateShift(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的班次ID"})
		return
	}

	var shift models.Shift
	result := h.DB.First(&shift, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "班次不存在"})
		return
	}

	var updatedShift models.Shift
	if err := c.ShouldBindJSON(&updatedShift); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的班次数据"})
		return
	}

	// 确保时间格式正确
	if updatedShift.StartTime.IsZero() || updatedShift.EndTime.IsZero() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "开始时间和结束时间不能为空"})
		return
	}

	// 如果不是全天班次，确保结束时间晚于开始时间
	if !updatedShift.IsFullDay {
		// 提取时间部分进行比较
		startHour, startMin, _ := updatedShift.StartTime.Clock()
		endHour, endMin, _ := updatedShift.EndTime.Clock()

		if endHour < startHour || (endHour == startHour && endMin <= startMin) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "下班时间必须晚于上班时间"})
			return
		}
	}

	// 更新字段
	shift.Name = updatedShift.Name
	shift.StartTime = updatedShift.StartTime
	shift.EndTime = updatedShift.EndTime
	shift.IsFullDay = updatedShift.IsFullDay
	shift.Description = updatedShift.Description
	shift.ProductID = updatedShift.ProductID
	shift.ProductName = updatedShift.ProductName

	result = h.DB.Save(&shift)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新班次失败"})
		return
	}

	c.JSON(http.StatusOK, shift)
}

// DeleteShift 删除班次
func (h *ShiftHandler) DeleteShift(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的班次ID"})
		return
	}

	var shift models.Shift
	result := h.DB.First(&shift, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "班次不存在"})
		return
	}

	// 检查是否有排班依赖此班次
	var count int64
	h.DB.Model(&models.Schedule{}).Where("shift_id = ?", id).Count(&count)
	if count > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无法删除班次，存在依赖的排班记录"})
		return
	}

	result = h.DB.Delete(&shift)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除班次失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "班次已删除"})
}
